package com.example.es.controller;

import com.example.es.dto.PromotionSearchRequest;
import com.example.es.entity.Promotion;
import com.example.es.service.PromotionService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/promotions")
public class PromotionController {

    @Autowired
    private PromotionService promotionService;

    @GetMapping
    public ResponseEntity<List<Promotion>> getAllPromotions() {
        List<Promotion> promotions = promotionService.findAll();
        return ResponseEntity.ok(promotions);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Promotion> getPromotionById(@PathVariable Long id) {
        Optional<Promotion> promotion = promotionService.findById(id);
        return promotion.map(ResponseEntity::ok)
                       .orElse(ResponseEntity.notFound().build());
    }

    @GetMapping("/active")
    public ResponseEntity<List<Promotion>> getActivePromotions() {
        List<Promotion> promotions = promotionService.findActivePromotions();
        return ResponseEntity.ok(promotions);
    }

    @GetMapping("/type/{type}")
    public ResponseEntity<List<Promotion>> getPromotionsByType(@PathVariable String type) {
        List<Promotion> promotions = promotionService.findByType(type);
        return ResponseEntity.ok(promotions);
    }

    @GetMapping("/discount/{minDiscountRate}")
    public ResponseEntity<List<Promotion>> getPromotionsByDiscount(@PathVariable Double minDiscountRate) {
        List<Promotion> promotions = promotionService.findByMinDiscountRate(minDiscountRate);
        return ResponseEntity.ok(promotions);
    }

    @PostMapping("/search")
    public ResponseEntity<List<Promotion>> searchPromotions(@Valid @RequestBody PromotionSearchRequest request) {
        List<Promotion> promotions = promotionService.searchPromotions(
            request.getName(),
            request.getType(),
            request.getMinDiscountRate(),
            request.getTags()
        );
        return ResponseEntity.ok(promotions);
    }

    @PostMapping
    public ResponseEntity<Promotion> createPromotion(@Valid @RequestBody Promotion promotion) {
        Promotion savedPromotion = promotionService.save(promotion);
        return ResponseEntity.ok(savedPromotion);
    }

    @PutMapping("/{id}")
    public ResponseEntity<Promotion> updatePromotion(@PathVariable Long id, @Valid @RequestBody Promotion promotion) {
        promotion.setId(id);
        Promotion updatedPromotion = promotionService.save(promotion);
        return ResponseEntity.ok(updatedPromotion);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deletePromotion(@PathVariable Long id) {
        promotionService.deleteById(id);
        return ResponseEntity.ok().build();
    }
}